package com.fullstack.landscape.editor.config;

import com.fullstack.landscape.editor.service.AttachmentService;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class AdditionalResourceWebConfiguration implements WebMvcConfigurer {

    public static final String ATTACHMENT_PATH_PREFIX = "/api/attachment/";

    private final AttachmentService attachmentService;

    public AdditionalResourceWebConfiguration(AttachmentService attachmentService) {
        this.attachmentService = attachmentService;
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/notFound").setViewName("forward:/index.html");
    }

    @Override
    public void addResourceHandlers(final ResourceHandlerRegistry registry) {
        String storeDir = attachmentService.getStoreDir() + "/";
        registry.addResourceHandler(ATTACHMENT_PATH_PREFIX + "**").addResourceLocations("file:" + storeDir);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "DELETE", "PUT")
                .maxAge(3600);
    }
}